import { toast } from "./index";
import axios, {
	AxiosRequestHeaders,
	AxiosResponse,
	InternalAxiosRequestConfig,
} from "axios";
import { history } from "./history";
import { SpecifiedLengthArray } from "./data";

export interface BaseResponse<D = unknown> {
	code: number;
	data?: D;
	message?: string;
}

export interface PageData<D> {
	data: D;
	total: string;
}

const request = axios.create({
	baseURL: process.env.REACT_APP_BASEURL,
	timeout: 20 * 1000,
});

const fixedTimeoutList = new SpecifiedLengthArray([], { maxLength: 5 });

type ExtendedConfig = InternalAxiosRequestConfig & { timeStamp: number };

request.interceptors.request.use((config) => {
	(config as ExtendedConfig).timeStamp = Date.now();
	let Authorization = "";
	try {
		Authorization = JSON.parse(
			localStorage.getItem("Authorization") as string
		);
		// eslint-disable-next-line no-empty
	} catch {}
	if (Authorization) {
		(
			config.headers as AxiosRequestHeaders
		).Authorization = `Bearer ${Authorization}`;
	}
	return config;
});

request.interceptors.response.use(
	(response: AxiosResponse<BaseResponse>) => {
		const { code = 500, message } = response.data;
		switch (code) {
			case 400:
				toast.error(message || "参数错误");
				break;
			case 401:
				toast.error("请先登录");
				if (localStorage.getItem("Authorization")) {
					localStorage.removeItem("Authorization");
				}
				history.replace("/auth");
				break;
			case 403:
				toast.error(message || "暂无权限");
				typeof message === "string" &&
					message.includes("冻结") &&
					history.replace("/403");
				break;
			case 404:
				toast.error("接口不存在");
				break;
			case 500:
				toast.error(message || "请求失败");
		}
		if (code === 200) {
			return Promise.resolve(response);
		} else {
			return Promise.reject(response.data);
		}
	},
	(error) => {
		const { status } = error.response || {};
		switch (status) {
			case 504:
				toast.error("请求超时");
				fixedTimeoutList.push(error);
				console.log(fixedTimeoutList);
				if (
					fixedTimeoutList.length === 5 &&
					fixedTimeoutList.array.every(
						(item) =>
							(item as { config: ExtendedConfig }).config
								.timeStamp +
								1000 >
							Date.now()
					)
				) {
					toast.error("服务器无响应，请稍后重试");
					history.replace("/auth");
				}
		}
		return Promise.reject(error);
	}
);

export default request;
